package info.monkeyws.AutoRinger;

import android.media.AudioFormat;
//import android.media.AudioManager;
import android.media.AudioRecord;
//import android.media.AudioTrack;
import android.media.MediaRecorder;

public class MicVolume {
	
	public static int getVolume(){
		
		int L = Settings.DEFAULT_MIC_SAMPLE_LENGTH;
		
		short[] myRecordedAudio = new short[L];
	    AudioRecord audioRecord = new AudioRecord(
	    		MediaRecorder.AudioSource.MIC, 
	    		11025, 
	    		AudioFormat.CHANNEL_IN_MONO, 
	    		AudioFormat.ENCODING_PCM_16BIT, 
	    		L);
	    	    
	    audioRecord.startRecording();
	    audioRecord.read(myRecordedAudio, 0, L);
	    audioRecord.stop();
	       	            
	    float volume = -1;
	    for (int i = 1; i<L-1; i++)
	    	volume+=Math.abs(myRecordedAudio[i]);
	    volume/=L;
	    
	    /*DEBUG: PLAY RECORDED
	    AudioTrack audioTrack = new AudioTrack(
		AudioManager.STREAM_MUSIC,
		11025,
		AudioFormat.CHANNEL_OUT_MONO,	
		AudioFormat.ENCODING_PCM_16BIT,
		4096,	
		AudioTrack.MODE_STREAM);
	    audioTrack.play();
	    audioTrack.write(myRecordedAudio, 0, 50000);
	    audioTrack.stop();
	    */
	    	    
		return (int)volume;		
	}
	
}
